package com.blq.web.CustomerRepair.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blq.api.domain.EvaluationBackup;
import com.blq.api.domain.MaterialAfter;
import com.blq.api.domain.MaterialBefore;
import com.blq.api.mapper.EvaluationBackupMapper;
import com.blq.api.mapper.MaterialAfterMapper;
import com.blq.api.mapper.MaterialBeforeMapper;
import com.blq.common.annotation.Log;
import com.blq.common.annotation.RepeatSubmit;
import com.blq.common.core.controller.BaseController;
import com.blq.common.core.domain.PageQuery;
import com.blq.common.core.domain.R;
import com.blq.common.core.domain.entity.SysDept;
import com.blq.common.core.domain.entity.SysUser;
import com.blq.common.core.page.TableDataInfo;
import com.blq.common.core.validate.AddGroup;
import com.blq.common.core.validate.EditGroup;
import com.blq.common.enums.BusinessType;
import com.blq.common.utils.ResultMsg;
import com.blq.common.utils.StringUtils;
import com.blq.common.utils.poi.ExcelUtil;
import com.blq.system.domain.SysOss;
import com.blq.system.domain.SysPost;
import com.blq.system.mapper.SysDeptMapper;
import com.blq.system.mapper.SysNoticeMapper;
import com.blq.system.mapper.SysOssMapper;
import com.blq.system.mapper.SysUserMapper;
import com.blq.system.service.ISysDeptService;
import com.blq.system.service.ISysPostService;
import com.blq.system.service.ISysUserService;
import com.blq.web.CustomerRepair.domain.CustomerRepair;
import com.blq.web.CustomerRepair.domain.bo.CustomerRepairBo;
import com.blq.web.CustomerRepair.domain.vo.CustomerRepairVo;
import com.blq.web.CustomerRepair.mapper.CustomerRepairMapper;
import com.blq.web.CustomerRepair.service.ICustomerRepairService;
import com.blq.web.PayoutInformation.domain.MaterialInfo;
import com.blq.web.PayoutInformation.domain.PayoutInformation;
import com.blq.web.PayoutInformation.mapper.MaterialInfoMapper;
import com.blq.web.PayoutInformation.mapper.PayoutInformationMapper;
import com.blq.web.customerMode.entiy.*;
import com.blq.web.customerMode.mapper.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 客户报修抢修Controller
 *
 * @author Blq
 * @date 2022-08-31
 */
@Validated
@Api(value = "客户报修抢修控制器", tags = {"客户报修抢修管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/web/CustomerRepair")
public class CustomerRepairController extends BaseController {

    private final ICustomerRepairService iCustomerRepairService;
    @Autowired
    private ComerController comerController;
    @Autowired
    private MaterialAfterMapper materialAfterMapper;
    @Autowired
    private MaterialBeforeMapper materialBeforeMapper;
    @Autowired
    private EvaluationBackupMapper evaluationBackupMapper;

    private final ISysUserService iSysUserService;
    @Autowired
    private CustomerRepairMapper customerRepairMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    private final ISysDeptService iSysDeptService;

    private final ISysPostService iSysPostService;
    @Autowired
    private MaterialInfoMapper materialInfoMapper;
    @Autowired
    private final SysDeptMapper baseMapper;
    @Autowired
    private TicketMapper ticketMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private InvestigationMapper investigationMapper;
    @Autowired
    private QuotationMapper quotationMapper;
    @Autowired
    private EvaluationMapper evaluationMapper;
    @Autowired
    private PayoutInformationMapper payoutInformationMapper;
    @Autowired
    private SysNoticeMapper sysNoticeMapper;
    @Autowired
    private SysOssMapper sysOssMapper;

    /**
     * 销售额、接单数统计查询
     * type：类型（1：销售额；2：接单数）（必传）
     * model：（day：日；week：周；month：月；year：年；area：区县；city：州市）必传
     * startDate：开始日期（可不传）
     * endDate：结束日期（可不传）
     * area：区县（可不传）
     * city：州市（可不传）
     * province：省份（可不传）
     */
    @ApiOperation("销售额、接单数统计查询")
    @GetMapping("/statTrendChart")
    public R<List<Map<String,Object>>> statTrendChart(TrendChartDto trendChart) {
        String type = trendChart.getType();
        List<Map<String,Object>> result;
        //1：销售额；2：接单数
        if ("1".equals(type)) {
            result = iCustomerRepairService.selectSalesVolume(trendChart);
        } else {
            result = iCustomerRepairService.selectReceiveNum(trendChart);
        }
        return R.ok(result);
    }

    /**
     * 人员销售额、接单数统计查询
     * type：类型（1：销售额；2：接单数）（可不传）
     * startDate：开始日期（可不传）
     * endDate：结束日期（可不传）
     * area：区县（可不传）
     * city：州市（可不传）
     * province：省份（可不传）
     */
    @ApiOperation("人员销售额、接单数统计查询")
    @GetMapping("/statUserOrder")
    public R<List<Map<String,Object>>> statUserOrder(TrendChartDto trendChart) {
        return R.ok(iCustomerRepairService.selectUserOrderAndPrice(trendChart));
    }

    /**
     * 查询客户报修抢修列表
     */
    @ApiOperation("查询客户报修抢修列表")
    @SaCheckPermission("web:CustomerRepair:list")
    @GetMapping("/list")
    public TableDataInfo<CustomerRepairVo> list(CustomerRepairBo bo, PageQuery pageQuery) {
        TableDataInfo<CustomerRepairVo> customerRepairVoTableDataInfo = iCustomerRepairService.queryPageList(bo, pageQuery);
        return customerRepairVoTableDataInfo;
    }

    /**
     * 导出客户报修抢修列表
     */
    @ApiOperation("导出客户报修抢修列表")
    @SaCheckPermission("web:CustomerRepair:export")
    @Log(title = "客户报修抢修", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CustomerRepairBo bo, HttpServletResponse response) {
        List<CustomerRepairVo> list = iCustomerRepairService.queryList(bo);
        ExcelUtil.exportExcel(list, "客户报修抢修", CustomerRepairVo.class, response);
    }

    /**
     * 获取客户报修抢修详细信息
     */
    @ApiOperation("获取客户报修抢修详细信息")
    @SaCheckPermission("web:CustomerRepair:query")
    @GetMapping("/{customerKey}")
    public R<CustomerRepairVo> getInfo(@ApiParam("主键") @NotNull(message = "主键不能为空") @PathVariable("customerKey") String customerKey) {
        return R.ok(iCustomerRepairService.queryById(customerKey));
    }

    /**
     * 新增客户报修抢修
     */
    @ApiOperation("新增客户报修抢修")
    @SaCheckPermission("web:CustomerRepair:add")
    @Log(title = "客户报修抢修", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CustomerRepairBo bo) {
        return toAjax(iCustomerRepairService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改客户报修抢修
     */
    @ApiOperation("修改客户报修抢修")
//    @SaCheckPermission("web:CustomerRepair:edit")
    @Log(title = "客户报修抢修", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/edit")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CustomerRepairBo bo) {
        return toAjax(iCustomerRepairService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除客户报修抢修
     */
    @ApiOperation("删除客户报修抢修")
    @SaCheckPermission("web:CustomerRepair:remove")
    @Transactional
    @Log(title = "客户报修抢修", businessType = BusinessType.DELETE)
    @DeleteMapping("/{customerKeys}")
    public R<Void> remove(@ApiParam("主键串") @NotEmpty(message = "主键不能为空") @PathVariable String[] customerKeys) {
        List<@NotEmpty(message = "主键不能为空") String> strings = Arrays.asList(customerKeys);
        for (String string : strings) {
            HashMap<String, Object> map = new HashMap<>();
            //评价备份表
            map.put("evaluation_id",string);
            evaluationBackupMapper.deleteByMap(map);
            map.clear();
            //删除评价
            map.put("evaluation_id",string);
            evaluationMapper.deleteByMap(map);
            map.clear();
            //勘察资料
            map.put("investigation_repari",string);
            investigationMapper.deleteByMap(map);
            map.clear();
            //施工之后的图片
            map.put("material_repari",string);
            materialAfterMapper.deleteByMap(map);
            map.clear();
            //施工之前的图片
            map.put("material_repari",string);
            materialBeforeMapper.deleteByMap(map);
            map.clear();
            //施工材料信息
            map.put("material_repari",string);
            materialInfoMapper.deleteByMap(map);
            map.clear();
            //收款信息表
            map.put("customer_key",string);
            payoutInformationMapper.deleteByMap(map);
            map.clear();
            //报价单
            map.put("quotation_repair",string);
            quotationMapper.deleteByMap(map);
            map.clear();
            //通知公告
            map.put("customer_key",string);
            sysNoticeMapper.deleteByMap(map);
            map.clear();
            //工单审核表
            map.put("ticket_repair",string);
            ticketMapper.deleteByMap(map);
            map.clear();
            //评论信息
            map.put("evaluation_id",string);
            evaluationMapper.deleteByMap(map);
            map.clear();
            //删除评价备份表
        }
        //删除工单表
        return toAjax(iCustomerRepairService.deleteWithValidByIds(strings, true) ? 1 : 0);
    }


    //web端订单详情页
    @GetMapping("Ecors/{customerKey}")
    public R<CustomerRepairVo> editMessage(@PathVariable("customerKey") String customerKey) {
        CustomerRepairVo customerRepairVo0 = new CustomerRepairVo();
        //第一页
        /**第一-------
         * 标题 : 维修类型
         * 工单编号
         * 发起人 :
         * 联系电话
         * 发起时间
         * 工单状态
         * 地址
         * 问题描述
         */
        //订单详情
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomerRepair customerRepair = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>().eq("customer_key", customerKey));
        if (customerRepair != null) {
            //发起人信息
            SysUser sysUser = comerController.getSysUserByUserId(customerRepair.getCustomerId());
            customerRepairVo0.setInitiator(sysUser.getNickName());//发起人名字
            customerRepairVo0.setWorkOrderStatus(customerRepair.getCustomerFlag());
            customerRepairVo0.setCustomerTimer(customerRepair.getCreateTime());
            customerRepairVo0.setAppointmentTime(customerRepair.getCustomerTimer());
            customerRepairVo0.setApplicationMaterial(customerRepair.getCustomerFiles());
            customerRepairVo0.setTurnoverTime(customerRepair.getUpdateTime());
            customerRepairVo0.setAssignmentType(customerRepair.getCustomerAuto());
            customerRepairVo0.setMaterialTime(customerRepair.getMaterialTime());
            BeanUtils.copyProperties(customerRepair, customerRepairVo0);
            //接单人信息
            if (customerRepair.getReceiverBy() != null) {
                String customerPlayer = customerRepair.getReceiverBy();
                SysUser sysUser1 = comerController.getSysUserByUserId(customerPlayer);
                customerRepairVo0.setDepartment1(comerController.getDepartmentName(sysUser1));
                customerRepairVo0.setReceiver(sysUser1.getNickName());
                customerRepairVo0.setAnswerASingleCall(sysUser1.getPhonenumber());
                customerRepairVo0.setTheUnitToWhichTheOrderBelongs(comerController.getDeptName(String.valueOf(sysUser1.getDeptId())));
            }
            //指派订单人信息
            if (customerRepair.getCustomerDesignate() !=null){
                String customerPlayer = customerRepair.getCustomerDesignate();
                SysUser sysUser1 = comerController.getSysUserByUserId(customerPlayer);
                customerRepairVo0.setDesignateDepartment1(comerController.getDepartmentName(sysUser1));
                customerRepairVo0.setDesignateReceiver(sysUser1.getNickName());
                customerRepairVo0.setDesignateAnswerASingleCall(sysUser1.getPhonenumber());
                customerRepairVo0.setDesignateTheUnitToWhichTheOrderBelongs(comerController.getDeptName(String.valueOf(sysUser1.getDeptId())));
                customerRepairVo0.setDesignateReceiveTime(customerRepair.getCustomerDesignateTime());
            }
            //转单人信息
            if (!StringUtils.isBlank(customerRepair.getCustomerUnit())){
                String customerUnit = customerRepair.getCustomerUnit();//转单人id
                SysUser transferSolo = comerController.getSysUserByUserId(customerUnit);//转单人对象
                //放入
                customerRepairVo0.setToReceiveTime(customerRepair.getCustomerTime());//转单时间
                customerRepairVo0.setToReceiver(transferSolo.getNickName());//转单人名字
                customerRepairVo0.setToAnswerASingleCall(transferSolo.getPhonenumber());//电话
                customerRepairVo0.setToTheUnitToWhichTheOrderBelongs(comerController.getDeptName(String.valueOf(transferSolo.getDeptId())));
                customerRepairVo0.setToDepartment1(comerController.getDepartmentName(transferSolo));//转单人部门名字
            }
            //提交审核
            Ticket ticketRepair = ticketMapper.selectOne(new QueryWrapper<Ticket>().eq("ticket_repair", customerKey));
            if (ticketRepair != null) {
                if (ticketRepair.getTicketEquip()!=null){
                    customerRepairVo0.setStatus(ticketRepair.getTicketReslover());//审核结果
                    if (ticketRepair.getTicketUser().length() > 25) {
                        //多人
                        String ticketReviewer1 = ticketRepair.getTicketUser();
                        String[] split3 = ticketReviewer1.split(",");
                        LinkedHashSet<String> strings = new LinkedHashSet<>();
                        for (int i = 0; i < split3.length; i++) {
                            String name = split3[i];
                            strings.add(name);
                        }
                        StringBuilder username = new StringBuilder();
                        StringBuilder deptname = new StringBuilder();//部门名字
                        StringBuilder unit = new StringBuilder();
                        StringBuilder phone = new StringBuilder();
                        //部门和单位去重
                        LinkedHashSet<String> highDepartment = new LinkedHashSet<>();
                        LinkedHashSet<String> department = new LinkedHashSet<>();
                        for (String string : strings) {
                            //用户名
                            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("user_id", Long.parseLong(string));
                            SysUser proposer = sysUserMapper.selectOne(queryWrapper);
                            username.append("," + proposer.getNickName());
                            //根据用户,当前部门拼接部门名字
                            String departmentName = comerController.getDepartmentName(proposer);
                            department.add(departmentName);
                            //单位
                            String deptName = comerController.getDeptName(String.valueOf(proposer.getDeptId()));
                            highDepartment.add(deptName);
                            //电话
                            phone.append("," + proposer.getPhonenumber());
                        }
                        department.forEach(a -> deptname.append("," + a));
                        highDepartment.forEach(a -> unit.append("," + a));
                        String substringusername = username.substring(1);
                        String substringdeptname = deptname.substring(1);
                        String substringunit = unit.substring(1);//部门名字
                        String substringphone = phone.substring(1);
                        customerRepairVo0.setApplicantTelephoneNumber(substringphone);
                        customerRepairVo0.setDepartment(substringdeptname);
                        customerRepairVo0.setAffiliatedUnit(substringunit);
                        customerRepairVo0.setProposer(substringusername);

                    } else {//单人
                        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("user_id", Long.parseLong(ticketRepair.getCreateBy()));
                        SysUser proposer = sysUserMapper.selectOne(queryWrapper);
                        customerRepairVo0.setApplicantTelephoneNumber(proposer.getPhonenumber());
                        customerRepairVo0.setDepartment(comerController.getDepartmentName(proposer));
                        customerRepairVo0.setAffiliatedUnit(comerController.getDeptName(String.valueOf(proposer.getDeptId())));
                        customerRepairVo0.setProposer(proposer.getNickName());
                    }
                    String[] split = ticketRepair.getTicketUser().split(",");
                    long count = Arrays.stream(split).count();
                    customerRepairVo0.setMaintenancePersonnel(String.valueOf(count));
                    BeanUtils.copyProperties(ticketRepair, customerRepairVo0);

                    //审核员
                    if (ticketRepair.getTicketReviewer() != null) {
                        customerRepairVo0.setAssessingOfficer(comerController.getSysUserByUserId(ticketRepair.getTicketReviewer()).getNickName());
                        //勘察信息
                        Investigation investigation_repari = investigationMapper.selectOne(new QueryWrapper<Investigation>().eq("investigation_repari", customerKey));
                        if (investigation_repari != null) {
                            BeanUtils.copyProperties(investigation_repari, customerRepairVo0);
                            try {
                                List<MaterialBefore> materialBefores = materialBeforeMapper.selectList(new QueryWrapper<MaterialBefore>()
                                        .eq("material_repari", customerKey).eq("ids","null"));
                                if (materialBefores.size()!=0) customerRepairVo0.setMaterialBefore(materialBefores);
                                customerRepairVo0.setInvestigationTime(simpleDateFormat.parse(investigation_repari.getInvestigationTime()));
                                customerRepairVo0.setInvestigationOver(simpleDateFormat.parse(investigation_repari.getInvestigationOver()));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                customerRepairVo0.setRemark(ticketRepair.getRemark());
            }
            //上传报价方案
            Quotation quotation_repair = quotationMapper.selectOne(new QueryWrapper<Quotation>().eq("quotation_repair", customerKey));
            if (quotation_repair != null) {
                customerRepairVo0.setQuotationScmorTime(quotation_repair.getCreateTime());
                BeanUtils.copyProperties(quotation_repair, customerRepairVo0);
            }
            //待客户付款
            PayoutInformation payout_key = payoutInformationMapper.selectOne(new QueryWrapper<PayoutInformation>().eq("customer_key", customerKey));
            if (payout_key != null) {
                BeanUtils.copyProperties(payout_key, customerRepairVo0);
                if (payout_key.getPaymentStatus().equals("1"))
                    customerRepairVo0.setCollectionStatus("已付款");
                if (payout_key.getPaymentStatus().equals("0"))
                    customerRepairVo0.setCollectionStatus("未付款");
                customerRepairVo0.setPayoutFrom(payout_key.getPayoutFrom());
                customerRepairVo0.setConfirmTheTimeOfPayment(payout_key.getConfirmTheTimeOfPayment());
                customerRepairVo0.setPayoutUser(payout_key.getPayoutUser());
                customerRepairVo0.setPayerSPhone(payout_key.getPayoutPhone());
                customerRepairVo0.setPhoneNumberOfTheContact("收款联系人");
                customerRepairVo0.setPayoutPrice(payout_key.getPayoutPrice().toString());

                SysOss sysOss = sysOssMapper.selectById(payout_key.getPayoutCode());
                if (sysOss != null) {
                    customerRepairVo0.setPayoutCode(sysOss.getUrl());
                }

                customerRepairVo0.setConfirmationOfPayer(payout_key.getConfirmationPaymentBy());//确认付款人
                customerRepairVo0.setConfirmTheTimeOfPayment(payout_key.getConfirmTheTimeOfPayment());//确认付款时间
                customerRepairVo0.setConfirmTheRecipient(payout_key.getConfirmTheRecipient());//确认到账人
                customerRepairVo0.setConfirmationPaymentTime(payout_key.getConfirmationPaymentTime());//确认到账时间
            }
            //完成施工
            MaterialInfo material_repari1 = materialInfoMapper.selectOne(new QueryWrapper<MaterialInfo>().eq("material_repari", customerKey));
            if (material_repari1 != null) {
                if (material_repari1.getMaterialIllustrate() != null)
                    customerRepairVo0.setMaterialIllustrate(material_repari1.getMaterialIllustrate());

                //之前的图片
                List<MaterialAfter> materialAfters = materialAfterMapper.selectList(new QueryWrapper<MaterialAfter>().eq("material_repari", customerKey));
                if (materialAfters.size()!=0) customerRepairVo0.setMaterialAfter(materialAfters);
                //之后的图片
                List<MaterialBefore> materialBefores = materialBeforeMapper.selectList(new QueryWrapper<MaterialBefore>().eq("material_repari", customerKey));
                if (materialBefores.size()!=0) customerRepairVo0.setMaterialBefore(materialBefores);

                if (material_repari1.getMaterialPower() != null)
                    customerRepairVo0.setMaterialPower(material_repari1.getMaterialPower());

                /*if (material_repari1.getMaterialTime() != null) {
                    try {
                        customerRepairVo0.setMaterialTime(simpleDateFormat.parse(material_repari1.getMaterialTime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }*/
                if (Objects.equals(material_repari1.getMaterialPower(), "0"))
                    customerRepairVo0.setMaterialPower("需要断电");
                if (Objects.equals(material_repari1.getMaterialPower(), "1"))
                    customerRepairVo0.setMaterialPower("无需断电");
            }
            //验收信息
            Evaluation evaluation_id = evaluationMapper.selectOne(new QueryWrapper<Evaluation>().eq("evaluation_id", customerKey));
            if (evaluation_id != null) {
                customerRepairVo0.setEvaluationStatus(evaluation_id.getEvaluationStatus());//评价星级
                customerRepairVo0.setEvaluationInfo(evaluation_id.getEvaluationInfo());//评级信息
                customerRepairVo0.setCheckAndAccept(evaluation_id.getEvaluationFlag());//是否通过验收
            }
            //验收备份信息
            List<EvaluationBackup> evaluation_id1 = evaluationBackupMapper.selectList(new QueryWrapper<EvaluationBackup>()
                    .eq("evaluation_id", customerKey));//格局订单号去查备份行数据

            List<MaterialAfter> materialAfters = materialAfterMapper.queryByIds(customerKey);
            for (EvaluationBackup backup : evaluation_id1) {
                List<MaterialAfter> materialAfterList = new ArrayList<>();
                for (MaterialAfter materialAfter : materialAfters) {
                    if (backup.getMaterialAfter().equals(materialAfter.getIds())) {
                        materialAfterList.add(materialAfter);
                    }
                }
//                backup.setMaterialAfterList(materialAfterList);
            }
            customerRepairVo0.setEvaluationBackupList(evaluation_id1);
            //关闭订单
            if (customerRepair.getClosingTime() != null) {
                BeanUtils.copyProperties(customerRepair, customerRepairVo0);
                SysUser sysUser2 = comerController.getSysUserByUserId(customerRepair.getClosingBy());
                customerRepairVo0.setOperator(sysUser2.getNickName());
                customerRepairVo0.setOperatorTelephone(sysUser2.getPhonenumber());
            }
        }
        return R.ok(customerRepairVo0);
    }
    @ApiOperation("已服务客户数、月环比和月同比数据查询")
    @GetMapping("/customerData")
    public R<Map<String,Object>> getServedCustomerData(@RequestParam String date) throws Exception {
        Map<String,Object> servedCustomerData = iCustomerRepairService.queryServedCustomerData(date);
        return R.ok(servedCustomerData);
    }
}
